package com.baomidou.springwind.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.springwind.entity.Project;
import com.baomidou.springwind.service.ProjectService;
import com.baomidou.springwind.utils.ParamMap;
import com.baomidou.springwind.utils.RequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.framework.controller.SuperController;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.springwind.service.IPermissionService;
import com.baomidou.springwind.service.IUserService;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 基础控制器
 * </p>
 *
 * @author hubin
 * @Date 2016-04-13
 */
public class BaseController extends SuperController implements HandlerInterceptor {

    @Autowired
    protected IUserService userService;

    @Autowired
    private IPermissionService permissionService;

    @Autowired
    private ProjectService projectService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        /*
         * 方法调用后调用该方法，返回数据给请求页
		 */
        if (isLegalView(modelAndView)) {
            modelAndView.addObject("currentUser", userService.selectById(getCurrentUserId()));
            modelAndView.addObject("menuList", permissionService.selectMenuVOByUserId(getCurrentUserId()));
            modelAndView.addObject("uniqueId", System.nanoTime());
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }

    /**
     * 判断是否为合法的视图地址
     * <p>
     *
     * @param modelAndView spring 视图对象
     * @return boolean
     */
    protected boolean isLegalView(ModelAndView modelAndView) {
        boolean legal = false;
        if (modelAndView != null) {
            String viewUrl = modelAndView.getViewName();
            if (viewUrl != null && viewUrl.contains("redirect:")) {
                legal = false;
            } else {
                legal = true;
            }
        }
        return legal;
    }

    /**
     * <p>
     * 转换为 bootstrap-table 需要的分页格式 JSON
     * </p>
     *
     * @param page 分页对象
     * @return
     */
    protected String jsonPage(Page<?> page) {
        JSONObject jo = new JSONObject();
        jo.put("recordsFiltered", page.getTotal());
        jo.put("recordsTotal", page.getTotal());
        jo.put("data", page.getRecords());
        return toJson(jo);
    }

    /**
     * <p>
     * 转换为 bootstrap-table 需要的分页格式 JSON
     * </p>
     *
     * @param page 分页对象
     * @return
     */
    protected String jsonPageOld(Page<?> page) {
        JSONObject jo = new JSONObject();
        jo.put("total", page.getTotal());
        jo.put("rows", page.getRecords());
        return toJson(jo);
    }

    @Override
    protected <T> Page<T> getPage(int size) {
        int _size = size, _index = 1;
        if (request.getParameter("_size") != null) {
            _size = Integer.parseInt(request.getParameter("_size"));
        }
        if (request.getParameter("_index") != null) {
            int _offset = Integer.parseInt(request.getParameter("_index"));
            _index = _offset / _size + 1;
        }
        return new Page<T>(_index, _size);
    }

    protected String booleanToString(boolean rlt) {
        return rlt ? "true" : "false";
    }

    protected String pjaxPath(String url, Model model) {
        String header = request.getHeader("X-PJAX");
        if (header == null || !header.equals("true")) {
            model.addAttribute("mainUrl", url);
            return "/index1";
        }
        return url;
    }

    protected ParamMap<String, Object> getParameterMap() {
        return RequestUtils.getParamMap(request);
    }

    protected String getProjectId() {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if ("prjId".equals(cookie.getName())) {
                return cookie.getValue();
            }
        }
        List<Project> projectList = projectService.getUserAllProjects();
        if (projectList.size() == 0) {
            return null;
        }
        return projectList.get(0).getId().toString();
    }
}
